package Test.sms;

import Test.ClearingDao;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import weaver.interfaces.schedule.BaseCronJob;
import weaver.mobile.plugin.ecology.service.PushNotificationService;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/*
 * 计划任务，发送清算消息到OA移动端
 */
public class SendClearingMsg extends BaseCronJob {
	private static ClearingDao clearingDao = new ClearingDao();

	@Override
	public void execute() {
		System.out.println("------计划任务： 发送清算消息------");
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");

		/* 从生产数据库获取当前最新清算日期 */
		// String sql1 = "select init_date from sysarg";
		// String dateSource1 = clearingDao.getClearingData(sql1,"MESSAGETREE");
		String dateSource1 = getDate();

		if (dateSource1 == null || dateSource1.equals("")) {
			System.out.println("SendClearingMsg: Error---读取不到生产清算日期数据 return");
			return;
		}
		Date date1 = null;// 生产最新清算日期
		try {
			date1 = sf.parse(dateSource1);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		/* 从OA数据库获取最新已清算日期 */
		String sql2 = "select qsrq from uf_xxsdata";
		String id = "";
		String dateSource2 = clearingDao.getClearingData(sql2);
		Date date2 = null;// OA最新清算日期
		if (dateSource2 == null || dateSource2.equals("")) {
			System.out.println("SendClearingMsg: Error---读取不到OA清算日期数据");
			try {
				date2 = sf.parse(dateSource1);// 将生产清算日期赋给OA清算日期，并写入OA数据库
				String tempSql = "insert into uf_xxsdata (qsrq,sfyfs) values ('" + dateSource1 + "',0)"; // 0表示未推送消息到OA
				clearingDao.insertModifyRecord(tempSql);
				id = clearingDao.getClearingData("select id from uf_xxsdata");
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			try {
				date2 = sf.parse(dateSource2);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// 查看date2是否已推送消息,如果没有发送，补发
			String value = clearingDao.getClearingData("select sfyfs from uf_xxsdata");
			id = clearingDao.getClearingData("select id from uf_xxsdata");
			if (value == null || value.equals("0") || value.equals("")) {
				// 开始发送
				sendMsg(dateSource2);
				String tempSql = "update uf_xxsdata set qsrq= '" + dateSource2 + "',sfyfs = 1 where id=" + id; // 1表示已推送消息到OA
				clearingDao.insertModifyRecord(tempSql);
			}
		}

		if (date2.before(date1)) {
			// 尚未发送
			sendMsg(dateSource1);
			String tempSql = "update uf_xxsdata set qsrq= '" + dateSource1 + "',sfyfs = 1 where id=" + id; // 1表示已推送消息到OA
			clearingDao.insertModifyRecord(tempSql);
		} else if (date2.after(date1)) {
			// 正常情况不应出现
			System.out.println("SendClearingMsg: Error -- OA清算日期after生产清算日期！！！");
		} else {
			// 日期相同，检查是否已发送
			String value = clearingDao.getClearingData("select sfyfs from uf_xxsdata");
			if (value == null || value.equals("0") || value.equals("")) {
				// 开始发送
				sendMsg(dateSource1);
				String tempSql = "update uf_xxsdata set qsrq= '" + dateSource1 + "',sfyfs = 1 where id=" + id; // 1表示已推送消息到OA
				clearingDao.insertModifyRecord(tempSql);
			} else {
				// 已发送过
				System.out.println("SendClearingMsg: Warning -- 已发送过");
			}
		}

	}

	/*
	 * 
	 * 获取生产日期数据，通过总线接口调用
	 */
	private String getDate() {
		String temp = httpRequest("http://172.16.203.7:8081/HTTPCHANNEL/HSSERVICE?funcno=912012&appid=1&sign=1", "GET");
		System.out.println(temp);
		String result = "";
		try {
			JSONObject obj = new JSONObject(temp);
			JSONObject json1 = (JSONObject) obj.get("result");
			JSONArray ary = (JSONArray) json1.get("dataset0");
			result = ary.getJSONObject(0).getString("init_date");
			System.out.println("生产日期数据: " + result);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	/*
	 * 
	 * 推送消息到OA String dateSource 需要推送的日期
	 */
	private void sendMsg(String dateSource) {
		//String receiveIds = "wuyf,liuyuc,suw";
		String receiveIds = clearingDao.getAllUserIds();
		PushNotificationService service = new PushNotificationService();
		Map<String, String> para = new HashMap<String, String>();
		para.put("module", "-2");
		para.put("messagetypeid", "34");// 消息树id
		// para.put("url", "http://www.baidu.com");

		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
		Date date = null;
		try {
			date = sf.parse(dateSource);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(date);
		int dayForWeek = 0;
		if (calendar.get(Calendar.DAY_OF_WEEK) == 1) {
			dayForWeek = 7;
		} else {
			dayForWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
		}

		if (dayForWeek == 1) {
			calendar.add(calendar.DATE, -3);// 把日期往后减三天
		} else {
			calendar.add(calendar.DATE, -1);// 把日期往后增加一天.整数往后推,负数往前移动
		}

		date = calendar.getTime();

		service.push(receiveIds, sf.format(date).toString() + " 清算已完成", 1, para);
		System.out.println(sf.format(date).toString() + " 消息已推送完成");
	}

	/**
	 * http请求
	 * 
	 * @param requestUrl
	 *            总线接口url
	 * @param requestMethod
	 *            Get/Post方法
	 * @return
	 */
	public String httpRequest(String requestUrl, String requestMethod) {

		String httpurl = requestUrl.substring(0, requestUrl.indexOf("?") + 1);
		String urlparam = requestUrl.substring(requestUrl.indexOf("?") + 1);
		try {
			requestUrl = httpurl + getUrlParamsByMap(getUrlParams(urlparam));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		StringBuilder respStrData = new StringBuilder();
		try {
			URL url = new URL(requestUrl);
			HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);

			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);
			httpUrlConn.connect();

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			// InputStreamReader inputStreamReader = new
			// InputStreamReader(inputStream,
			// Constants.CHARACTER_ENCODING_UTF8);
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str;
			while ((str = bufferedReader.readLine()) != null) {
				respStrData.append(str);
			}

			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			httpUrlConn.disconnect();
		} catch (ConnectException ce) {
			ce.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return respStrData.toString();
	}

	private Map<String, Object> getUrlParams(String param) {
		Map<String, Object> map = new HashMap<String, Object>(0);
		if (isEmpty(param)) {
			return map;
		}
		String[] params = param.split("&");
		for (int i = 0; i < params.length; i++) {
			String[] p = params[i].split("=");
			if (p.length == 2) {
				map.put(p[0], p[1]);
			}
		}
		return map;
	}

	private String getUrlParamsByMap(Map<String, Object> map) throws UnsupportedEncodingException {
		if (map == null) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			sb.append(entry.getKey() + "=" + URLEncoder.encode((String) entry.getValue(), "UTF-8"));
			sb.append("&");
		}
		String s = sb.toString();
		if (s.endsWith("&")) {
			s = org.apache.commons.lang.StringUtils.substringBeforeLast(s, "&");
		}
		return s;
	}

	private boolean isEmpty(String str) {
		if (str == null || str.length() == 0)
			return true;
		return false;
	}

}
